<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="" id="form">
        <input type="text" name="name" id="ipt">
        <input type="text" name="age" id="ipt">
        <input type="text" name="sex" id="ipt">
        <button id="btn">点击查询</button>
    </form>


        <script>
              //获取元素
        const oForm = document.getElementById('form');
        const oBtn = document.getElementById('btn')
        const oIpn = document.querySelector('#form input[name=name]')
        const oAge = document.querySelector('#form input[name=age]')
        const oSex = document.querySelector('#form input[name=sex]')
        //给表单绑定事件
        oForm.onsubmit = function(){
            //获取输入的值
            const nameValue = oIpn.value;
            const ageValue = oAge.value;
            const sexValue = oSex.value;
            //实例化
            const xhr  = new XMLHttpRequest();
            //打开路径
            //三个参数 1.请求方式   2.请求路径   3.是否用异步
            
            xhr.open('POST', `/addName`,true);
            //发送
            // xhr.send(JSON.stringify({
            //     name
            // }));
            // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            xhr.send(JSON.stringify({
                name:nameValue,
                age: ageValue,
                sex: sexValue
            }))
            //绑定事件
            xhr.onreadystatechange=function(){
                if(xhr.readyState ===4 &&(xhr.status >=200 && xhr.status <= 299)){
                    const data = JSON.parse(xhr.responseText)
                    console.log(data);
                }
            }
            return false 
        }
        </script>
    
</body>
</html>